package ar.utn.jess.common;

import java.util.Date;

import ar.utn.jess.exception.InvalidDataException;

public class TypeConverter {

	/**
	 * Converts a String to a certain data type (Long, Integer, Boolean, Date, Double)
	 */
	@SuppressWarnings("unchecked")
	public static Object convert(Class classConvertTo, String valueToConvert) throws InvalidDataException{
		Object result = null;
		
		if(valueToConvert != null) {			
			if(classConvertTo.equals(String.class))
				result = valueToConvert;
			else if(classConvertTo.equals(Integer.class) && !valueToConvert.isEmpty()) {
				try {
					result = Integer.parseInt(valueToConvert); 
				}
				catch(NumberFormatException e) { 
					throw new InvalidDataException(e);
				} 
			}
			else if(classConvertTo.equals(Long.class) && !valueToConvert.isEmpty()) {
				try {
					result = Long.parseLong(valueToConvert); 
				}
				catch(NumberFormatException e) { 
					throw new InvalidDataException(e);
				} 
			}
			else if(classConvertTo.equals(Double.class) && !valueToConvert.isEmpty()) {
				try {
					result = Double.parseDouble(valueToConvert); 
				}
				catch(NumberFormatException e) { 
					throw new InvalidDataException(e);
				} 
			}
			else if(classConvertTo.equals(Date.class) && !valueToConvert.isEmpty()) {
				result = DateUtil.stringToDate(valueToConvert);
			}			
			else if(classConvertTo.equals(Boolean.class) && !valueToConvert.isEmpty()) {
				result = (valueToConvert.toLowerCase().equals("true") || valueToConvert.toLowerCase().equals("t") || valueToConvert.equals("1"));
			}
			else if(classConvertTo.equals(AbstractEntity.class) && !valueToConvert.isEmpty()) {
				try {
					result = Integer.parseInt(valueToConvert); 
				}
				catch(NumberFormatException e) { 
					throw new InvalidDataException(e);
				} 
			}
			else if(classConvertTo.isEnum()) {
				result = valueToConvert;				
			}
		}
		
		return result;
	}
}
